package FenxiaoService

import (
	"context"
	"errors"
	toolsDb "gdshop-back-end-go/common/db"
	"gdshop-back-end-go/common/entity"
	"gdshop-back-end-go/common/libs/myCache"
	"gdshop-back-end-go/common/tools/mylog"
	"github.com/gogf/gf/errors/gerror"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/gconv"
	"time"
)

// 当前文件前后端API通用

func GetFenxiaoUserModelByMemberId(ctx context.Context, memberId int) (*entity.FenxiaoUser, error) {
	var fuList []*entity.FenxiaoUser
	all, err := myCache.GetOrSetFunc("table:fenxiao_user_all", func() (interface{}, error) {
		all, err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "fenxiao_user").All()
		if err != nil {
			return nil, err
		}
		return all, nil
	}, 600*time.Second)
	if err != nil {
		return nil, err
	}
	err = gconv.Scan(all, &fuList)
	if err != nil {
		return nil, err
	}
	if fuList == nil {
		return nil, gerror.NewCode(6000, "fenxiao_user 没有数据")
	}

	for _, item := range fuList {
		if item.MemberId == memberId {
			return item, nil
		}
	}
	return nil, gerror.NewCode(6000, "fenxiao_user 没有找到数据")
}

// GetMemberLevel 获取用户等级
func GetMemberLevel(ctx context.Context, memberId int) (*entity.FenxiaoLevel, error) {
	fuModel, err := GetFenxiaoUserModelByMemberId(ctx, memberId)
	if err != nil {
		if gerror.Code(err) != 6000 {
			mylog.ErrorLog("GetMemberLevel GetFenxiaoUserModelByMemberId " + err.Error())
			return nil, err
		}
		return nil, err
	}
	if fuModel == nil {
		// 不代表是错误，有可能当前用户不是分销商
		return nil, gerror.NewCode(6001, "没有找到数据")
	}

	if fuModel.Status == 0 {
		// 用户 被禁用
		return nil, gerror.NewCode(6002, "分销商被禁用")
	}
	var flModel *entity.FenxiaoLevel
	err = toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "fenxiao_level").Cache(600*time.Second).Where("id", fuModel.LevelId).Scan(&flModel)
	if err != nil {
		mylog.ErrorLog("GetMemberRate fenxiao_level " + err.Error())
		return nil, err
	}

	if flModel == nil {
		// 等级找不到，应该报错
		return nil, errors.New("fenxiao_level 找不到数据")
	}

	return flModel, nil
}

func GetMemberLevelId(ctx context.Context, memberId int) int {
	flModel, err := GetMemberLevel(ctx, memberId)
	if err != nil {
		return 0
	}
	return flModel.Id
}

// GetMemberLevelRate 获取会员 所属等级 佣金比例
// level 为 0 时，自动获取是店内自购还是上级佣金
func GetMemberLevelRate(ctx context.Context, memberId, level int) float64 {
	if memberId < 1 {
		return 0
	}
	rate, err := myCache.GetOrSetFunc("GetMemberRate:"+gconv.String(memberId)+":"+gconv.String(level), func() (interface{}, error) {
		if !ConfigLevelConfig() {
			// 未开启分销
			return 0, nil
		}
		config, err := GetConfig()
		if err != nil {
			//mylog.ErrorLog("ConfigLevelConfig " + err.Error())
			return 0, err
		}

		// 获取用户等级
		flModel, err := GetMemberLevel(ctx, memberId)
		if err != nil {
			errCode := gerror.Code(err)
			switch errCode {
			case 6000, 6001, 6002: // 没有找到数据的，直接返回
				return 0, err
			}
			// 不在上面的错误码，则返回错误
			return nil, err
		}

		// 店内自购 开启
		switch level {
		case 0:
			if config.SelfPurchaseRebate == 1 {
				// 开启自购佣金
				return float64(flModel.OneRate) / 100000.00, nil
			}
			return float64(flModel.TwoRate) / 100000.00, nil
		case 1:
			return float64(flModel.OneRate) / 100000.00, nil
		case 2:
			return float64(flModel.TwoRate) / 100000.00, nil
		case 3:
			return float64(flModel.ThreeRate) / 100000.00, nil
		default:
			return 0, nil
		}
	}, 600*time.Second)
	if err != nil {
		mylog.ErrorLog("GetMemberRate GetOrSetFunc 错误", err.Error())
		return 0
	}
	return gconv.Float64(rate)
}

// GetGoodsLevel 获取指定商品的分销设置数据
func GetGoodsLevel(ctx context.Context, goodsId, levelId int) (*entity.FenxiaoGoodsLevel, error) {
	var fglModel *entity.FenxiaoGoodsLevel
	err := toolsDb.GetUnSafaTable(ctx, "fenxiao_goods").As("fg").
		LeftJoin("fenxiao_goods_level fgl", "fgl.fenxiao_goods_id = fg.id").Fields("fgl.*").
		Where(g.Map{
			"fg.delete_at < ?": 1,
			"fg.goods_id":      goodsId,
			"fg.status":        1,
			"fgl.level_id":     levelId,
		}).Scan(&fglModel)

	if err != nil {
		return nil, err
	}

	return fglModel, nil
}

// GetMemberGoodsDetailsBrokerage 在商品详情，获取显示的佣金
func GetMemberGoodsDetailsBrokerage(ctx context.Context, memberId, goodsId int) float64 {
	config, err := GetConfig()
	if err != nil {
		mylog.ErrorLog("GetConfig " + err.Error())
		return 0
	}
	//  是否显示一级佣金
	if config.IsCommissionMoney == 0 {
		mylog.InfoLog("GetConfig 不开启佣金显示")
		// 不开启佣金显示
		return 0
	}

	flModel, err := GetMemberLevel(ctx, memberId)
	if err != nil {
		mylog.InfoLog("GetMemberLevel 获取返回")
		// 找不到分销商等级，返回 0
		return 0
	}
	// 获取到商品 等级 设置
	fglModel, err := GetGoodsLevel(ctx, goodsId, flModel.Id)
	if err != nil {
		mylog.ErrorLog("GetMemberGoodsDetailsBrokerage GetGoodsLevel " + err.Error())
		return 0
	}

	if fglModel == nil {
		// 有可能不存在数据的时候，说明没活动
		//mylog.ErrorLog("GetMemberGoodsDetailsBrokerage GetGoodsLevel 找不到数据")
		return 0
	}
	var rate float64
	if config.SelfPurchaseRebate == 1 {
		// 开启自购佣金
		rate = float64(fglModel.OneRate) / 100000.00
	} else {
		// 正常模式
		rate = float64(fglModel.TwoRate) / 100000.00
	}

	// 取出规格最高价钱
	maxPrice, err := toolsDb.GetUnSafaTable(ctx, "goods_option").As("go").LeftJoin("goods g", "go.goods_id = g.id").Where(
		"g.delete_at<1 AND go.delete_at<1 AND go.is_open = 1 AND go.goods_id = ?", goodsId).Max("go.sell_price")
	if err != nil {
		mylog.ErrorLog("GetMemberGoodsBrokerage goods_option " + err.Error())
		return 0
	}

	return rate * maxPrice
}
